package com.swift.service.menu.impl;

import com.swift.common.constant.CommonConstant;
import com.swift.core.menu.dto.MenuDto;
import com.swift.core.menu.dto.SubMenuDto;
import com.swift.core.menu.response.MenuRes;
import com.swift.mapper.menu.MenuMapper;
import com.swift.service.menu.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description :
 * @date 2022/06/18 16:27
 * @since open jdk 1.8
 */
@Service
public class MenuServiceImpl implements MenuService {
    private Logger logger = LoggerFactory.getLogger(MenuServiceImpl.class);

    @Resource
    private MenuMapper menuMapper;

    @Override
    public Map<String, List<MenuDto>> queryMenuInfo() {
        logger.info("获取菜单信息");
        return getMenuMap(menuMapper.queryMainMenuInfo(), menuMapper.querySubMenuInfo());
    }

    private static Map<String, List<MenuDto>> getMenuMap(List<MenuDto> menuDtoList, List<SubMenuDto> subMenuDtoList) {
        Map<String, List<MenuDto>> menuMap = new HashMap<>();
        List<MenuDto> menuList = new ArrayList<>();
        for (MenuDto mainMenu : menuDtoList) {
            List<SubMenuDto> subMenuDtos = new ArrayList<>();
            for (SubMenuDto subMenu : subMenuDtoList) {
                if(mainMenu.getMid() == subMenu.getParentId() ){
                    subMenuDtos.add(subMenu);
                    mainMenu.setSubMenuList(subMenuDtos);
                }
            }
            menuList.add(mainMenu);
        }
        //排序
        menuList.sort(Comparator.comparing(MenuDto::getMid).thenComparing(MenuDto::getMid));
        menuMap.put(CommonConstant.MENUS_KEY, menuList);
        return menuMap;
    }
}
